<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Pc_Gallery extends Stourweb_Controller
{
    private $_id = NULL;
    private $_user_info = NULL;

    /**
     * 初始化支付对象
     */
    public function before()
    {
        parent::before();
        //登录状态判断
        $this->_id = Cookie::get('st_supplier_id');
        if (empty($this->_id)) {
            $this->request->redirect('pc/login');
        } else {
            $this->_user_info = Model_Supplier::get_supplier_byid($this->_id);
        }
    }

    public function action_index()
    {
        $this->display('gallery/index');
    }

    public function action_recycle_bin()
    {
        $this->display('gallery/recycle_bin');
    }

    public function action_ajax_get_photo()
    {
        $level = Arr::get($_POST, 'level');

        $gallery = DB::select()->from('image_group')
            ->where('belong_type_id', '=', $this->_id)
            ->and_where('level', '=', $level)
            ->order_by('group_id', 'asc')
            ->execute()->as_array();

        echo json_encode($gallery);
    }

    public function action_ajax_get_photo_img()
    {
        $group_id = Arr::get($_POST, 'group_id');

        $image = DB::select()->from('image')
            ->where('group_id', '=', $group_id)
            ->order_by('id', 'DESC')
            ->execute()->as_array();

        echo json_encode($image);
    }

    public function action_ajax_add_photo()
    {
        try {
            $photo_name = Arr::get($_POST, 'photo_name');
            $group_id   = Arr::get($_POST, 'group_id');
            $level      = Arr::get($_POST, 'level', 2);
            $params     = [
                'photo_name'  => $photo_name,
                'group_id'    => $group_id,
                'supplier_id' => $this->_id,
                'level'       => $level
            ];
            $res        = Model_Supplier_Gallery::save_gallery($params, '系统供应商组');
        } catch (Exception $e) {
            $res = [
                'status' => false,
                'msg'    => $e->getMessage()
            ];
        }

        echo json_encode($res);
    }

    public function action_ajax_update_name()
    {
        $group_id = Arr::get($_POST, 'group_id');
        $name     = Arr::get($_POST, 'name');

        DB::update('image_group')->set(['group_name' => $name])->where('group_id', '=', $group_id)->execute();

        echo json_encode(['status' => true]);
    }

    public function action_ajax_update_img_name()
    {
        $img_id     = Arr::get($_POST, 'img_id');
        $image_name = Arr::get($_POST, 'image_name');
        $image_name = preg_replace("/[,\.;\?\s]/", "", $image_name);
        DB::update('image')->set(['image_name' => $image_name])->where('id', '=', $img_id)->execute();

        echo json_encode(['status' => true]);
    }

    public function action_ajax_delete_photo()
    {
        try {
            $group_id = Arr::get($_POST, 'group_id');
            $group    = $this->find_group_child($group_id);
            array_unshift($group, $group_id);
            $data = array(
                'name'        => '',
                'content'     => array(),
                'supplier_id' => $this->_id
            );
            foreach ($group as $k => $item) {
                list(, $path) = $this->_find_group_parent($item);
                if ($k == 0) {
                    $data['name'] = $path[count($path) - 1];
                }
                $image  = DB::select()->from('image')->where('group_id', '=', $item)->execute()->as_array();
                $single = array(
                    'path' => implode('|$|', $path),
                    'data' => array()
                );
                foreach ($image as $value) {
                    unset($value['id'], $value['group']);
                    array_push($single['data'], $value);
                }
                array_push($data['content'], $single);
            }
            $data['content'] = serialize($data['content']);
            list(, $rows) = DB::insert('image_recycle', array_keys($data))->values(array_values($data))->execute();
            if ($rows) {
                $group = implode(',', $group);
                //删除分类
                DB::delete('image_group')->where('group_id', 'in', DB::expr("({$group})"))->execute();
                //删除图片
                DB::delete('image')->where('group_id', 'in', DB::expr("({$group})"))->execute();
            }

            $res = [
                'status' => true
            ];
        } catch (Exception $e) {
            $res = [
                'status' => false,
                'msg'    => $e->getMessage()
            ];
        }

        echo json_encode($res);
    }

    private function find_group_child($group_id)
    {
        static $group = array();
        if (!$group) {
            $group = DB::select()->from('image_group')->execute()->as_array();
        }
        $group_list = array($group_id);
        list($data, $i) = array(
            array(),
            0
        );
        while ($i < 10000 && ($group_id = array_shift($group_list)) !== null) {
            foreach ($group as $item) {
                if ($item['pid'] == $group_id) {
                    array_push($group_list, $item['group_id']);
                    array_push($data, $item['group_id']);
                }
            }
            $i++;
        }
        return $data;
    }

    private function _find_group_parent($group_id)
    {
        static $group;
        if (is_null($group)) {
            $group = DB::select()->from('image_group')->execute()->as_array();
        }
        list($i, $data) = array(
            0,
            array(
                array(),
                array()
            )
        );
        while ($i < 1000) {
            if ($group_id) {
                foreach ($group as $item) {
                    if ($item['group_id'] == $group_id) {
                        array_unshift($data[0], $item['group_id']);
                        array_unshift($data[1], $item['group_name']);
                        $group_id = $item['pid'];
                    }
                }
            } else {
                break;
            }
        }
        return $data;
    }

    public function action_ajax_delete_photo_img()
    {
        try {
            $img_id = Arr::get($_POST, 'img_id');

            $image  = DB::select()->from('image')->where('id', 'in', DB::expr("($img_id)"))->execute()->as_array();
            $config = include BASEPATH . '/plugins/image_qiniu/config/image.php';
            $config = $config['qiniu'];
            if ($image) {
                list(, $path) = $this->_find_group_parent($image[0]['group_id']);
                $path = implode('|$|', $path);
                foreach ($image as $item) {
                    $original            = $item;
                    $data['url']         = $item['url'];
                    $data['supplier_id'] = $this->_id;
                    $data['name']        = $item['image_name'];
                    unset($original['id'], $original['group_id']);
                    $data['content'] = serialize(array(
                        array(
                            'path' => $path,
                            'data' => array($original)
                        )
                    ));
                    DB::insert('image_recycle', array_keys($data))->values(array_values($data))->execute();

                    //同步删除七牛
                    if ($config['is_open'] == 1) {
                        Model_Qiniu::delete_image($config, $item['url']);
                    }

                }
                DB::delete('image')->where('id', 'in', DB::expr("($img_id)"))->execute();
            }

            $res = [
                'status' => true
            ];
        } catch (Exception $e) {
            $res = [
                'status' => false,
                'msg'    => $e->getMessage()
            ];
        }
        echo json_encode($res);
    }

    public function action_ajax_get_recycle_bin_data()
    {
        $list = DB::select()->from('image_recycle')
            ->where('supplier_id', '=', $this->_id)
            ->order_by('id', 'desc')
            ->execute()->as_array();
        foreach ($list as &$v) {
            $v['url'] = $v['url'] ?: '/supplier/public/pc/images/nopic.gif';
        }

        echo json_encode($list);
    }

    public function action_ajax_reduction_photo()
    {
        $id_str = implode(',', $_POST['recycle_id']);
        $data   = DB::select()->from('image_recycle')->where('id', 'in', DB::expr("({$id_str})"))->execute()->as_array();
        foreach ($data as $item) {
            $item['content'] = unserialize($item['content']);
            foreach ($item['content'] as $sub_item) {
                $group_id = $this->_find_group_id($sub_item['path']);
                foreach ($sub_item['data'] as $k => $value) {
                    $value['group_id']       = $group_id;
                    DB::insert('image', array_keys($value))->values(array_values($value))->execute();
                }
            }
        }
        $rows = DB::delete('image_recycle')->where('id', 'in', DB::expr("({$id_str})"))->execute();

        echo json_encode(array('status' => $rows ? true : false));
    }

    private function _find_group_id($path)
    {
        $path = explode('|$|', $path);
        $pid  = 0;
        foreach ($path as $k => $item) {
            $group = DB::select()->from('image_group')
                ->where('pid', '!=', 0)
                ->and_where('group_name', '=', $item)
                ->and_where('belong_type_id', '=', $this->_id)
                ->execute()->current();
            if ($group) {
                $pid = $group['group_id'];
            } else {
                $data = array(
                    'group_name'     => "{$item}",
                    'pid'            => $pid,
                    'belong_type'    => 1,
                    'level'          => 2,
                    'belong_type_id' => $this->_id
                );
                list($pid) = DB::insert('image_group', array_keys($data))->values($data)->execute();
            }
        }
        return $pid;
    }

    public function action_ajax_delete_recycle()
    {
        $recycle_id = Arr::get($_POST, 'recycle_id');

        DB::delete('image_recycle')->where('id', '=', $recycle_id)->execute();

        echo json_encode(['status' => true]);
    }
}